package com.powerdata.framework.util;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

/**
 * 获取spring容器中的bean工具类，需要在spring配置文件中定义为Bean
 * @author he.xx
 */
public class SpringContextHolder implements ApplicationContextAware {
	private static ApplicationContext applicationContext;
	
	@Override
	public void setApplicationContext(ApplicationContext act) throws BeansException {
		applicationContext = act;
	}
	
	public static <T> T getBean(String name) {
		checkApplicationContext();
		return (T) applicationContext.getBean(name);
	}
	
	public static <T> T getBean(Class<T> requireType) {
		checkApplicationContext();
		return applicationContext.getBean(requireType);
	}
	
	public static ApplicationContext getApplicationContext() {
		checkApplicationContext();
		return applicationContext;
	}
	
	public static void checkApplicationContext() {
		if (applicationContext == null) {
			throw new IllegalStateException("applicaitonContext未注入,请在applicationContext.xml定义SpringContextHolder");
		}
	}
	
	public static void cleanApplicationContext() {
		applicationContext = null;
	}
	
}
